package com.zn.opit.tech.easyexcel.utils;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelUtil {

    public static List<String> getPropNameCns(Class<?> cls) {
        try {
            return getPropNameCns(cls.newInstance(), new ArrayList<>());
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<String> getPropNameCns(Object obj, List<String> propNames) {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (String.class.equals(field.getType())) {
                ExcelProperty annotation = field.getAnnotation(ExcelProperty.class);
                //原来的数组
                String[] value = annotation.value();
                if (value.length == 0) continue;
                propNames.add(value[0]);
            } else if(List.class.equals(field.getType())) {
                // 当前集合的泛型类型
                Type genericType = field.getGenericType();
                if (genericType instanceof ParameterizedType) {
                    ParameterizedType pt = (ParameterizedType) genericType;
                    // 得到泛型里的class类型对象
                    Class<?> actualTypeArgument = (Class<?>)pt.getActualTypeArguments()[0];
                    try {
                        getPropNameCns(actualTypeArgument.newInstance(), propNames);
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return propNames;
    }

    public static List<String> getPropNameEns(Class<?> cls) {
        List<String> list = new ArrayList<>();
        Field[] fields = new Field[0];
        try {
            fields = cls.newInstance().getClass().getDeclaredFields();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        for (Field field : fields) {
            list.add(field.getName());
        }
        return list;
    }

}
